var hituns_now = {};


var newDate_year_month_day = newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate();
var newDate_year_month = newDate.getFullYear() + '-' + (newDate.getMonth() + 1);
var newDate_month = (newDate.getMonth() + 1);
var newDate_year = newDate.getFullYear();
var fileUrl = '/json/hituns/tramendous?date=' + newDate_year_month_day + '&sum=false';

var nameChange = {
    'adsb': '航空ads-b数据',
    'ais': '船舶ais数据',
    'traffic': '交调实时数据',
    'airport': '机场大巴',
    'gps_js': '两客一危江苏',
    'gps_sh': '两客一危上海',
    'gps_zj': '两客一危浙江',
    'ali': '路况预测信息',
    'yys': '路况实时信息',
    'taxi': '出租车GPS',
    'gsevent': '高速事件数据',
    'gskk': '高速卡口数据'
}
var subCount = {
    'adsb': '浙江省交通运输厅、阿里云、浙江电子口岸、宁波市交通委、舟山市交通运输局、浙江省机场管理局',
    'ais': '浙江省交通运输厅、浙江电子口岸、温州市交通运输局、舟山市交通运输局',
    'traffic': '浙江省交通运输厅、上海云砥信息科技有限公司',
    'airport': '浙江省交通运输厅',
    'gps_js': '浙江省交通运输厅',
    'gps_sh': '浙江省交通运输厅、阿里云、江苏邮电规划设',
    'gps_zj': '浙江省交通运输厅、阿里云、浙江电子口岸、高德、江苏省交通运输厅、上海市交通委、浙江省公安厅、浙江省高速交警总队、浙江省道路运输管理局、江苏邮电规划设计院、金华市交通运输局、衢州市交通运输局、绍兴市交通运输局',
    'ali': '浙江省交通运输厅',
    'yys': '浙江省交通运输厅、阿里云、浙江电子口岸、杭州市交通运输局、金华市交通运输局、宁波市公路管理局、绍兴市交通运输局、浙江省政府（数管中心）、温州市交通运输局、浙江省高速交警总队',
    'taxi': '浙江省交通运输厅',
    'gsevent': '浙江省交通运输厅、百度、浙江电子口岸、杭州市交通运输局、金华市交通运输局、宁波市公路管理局、绍兴市交通运输局、温州市交通运输局、舟山市交通运输局',
    'gskk': '浙江省交通运输厅、百度、阿里云、浙江电子口岸、杭州交通运输局、湖州市交通运输局、金华市交通运输局、嘉兴市交通运输局、宁波交通委、宁波市公路管理局、绍兴市交通运输局、浙江省政府（数管中心）、温州市交通运输局、舟山市交通运输局'
}
var monthStr = '';
var fileUrl_sum = '';
var fileUrl_notsum = '';
var deepCopy = function (o) {
    if (o instanceof Array) {
        var n = [];
        for (var i = 0; i < o.length; ++i) {
            n[i] = deepCopy(o[i]);
        }
        return n;

    } else if (o instanceof Object) {
        var n = {}
        for (var i in o) {
            n[i] = deepCopy(o[i]);
        }
        return n;
    } else {
        return o;
    }
}
var start = function (chunk) {
    if (Object.keys(sum_now).length == 0 || newDate != sum.dates[sum.dates.length - 1]) {
        sum_now = deepCopy(chunk);
        sum_now.dates.pop();
        sum_now.values[0].data.pop();
        sum_now.values[1].data.pop();
        sum_now.values[2].data.pop();
        sum_now.values[0].color = '#ff7b8b';
        sum_now.values[1].color = '#f6bf5b';
        sum_now.values[2].color = '#6cc5ff';
        Highcharts.chart('chart', {
            chart: {
                type: 'areaspline',
                backgroundColor: 'rgba(255,255,255,0)',
                plotBackgroundColor: 'rgba(255,255,255,.1)',
                zoomType: 'x'
            },
            title: {
                text: null,
            },
            legend: {
                enabled: false
            },
            xAxis: {
                categories: sum_now.dates,
                tickmarkPlacement: 'on',
                tickLength: 5,
                tickWidth: 5,
                tickColor: "#7ba1ce",
                labels: {
                    style: {
                        "fontSize": '16px',
                        "fontFamily": 'Microsoft YaHei',
                        "color": '#fff'
                    }
                }
            },
            yAxis: {
                title: {
                    text: '(万条)',
                    x: -20,
                    y: -165,
                    rotation: 0,
                    style: {
                        color: '#fff'
                    }
                },
                gridLineWidth: 0,
                lineWidth: 1,
                labels: {
                    enabled: true,
                    formatter: function () {
                        return parseInt(this.value / 10000)
                    },
                    style: {
                        "fontSize": '16px',
                        "fontFamily": 'Microsoft YaHei',
                        "color": "#fff"
                    }
                },
            },
            tooltip: {
                valueSuffix: ' 万条',
                enabled: false,
                formatter: function () {
                    return parseInt(this.y / 10000) + ' 万条';
                }
            },
            credits: {
                enabled: false
            },
            plotOptions: {
                areaspline: {
                    fillOpacity: 0.5
                },
                series: {
                    dataLabels: {
                        enabled: true,
                        color: '#fff',
                        formatter: function () {
                            return parseInt(this.y / 10000) + ' 万条'
                        }
                    }
                }
            },
            series: sum_now.values
        });
    }
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var dates = date.getDate();
    document.getElementsByClassName('year')[0].innerHTML = year + "年";
    document.getElementsByClassName('time')[0].innerHTML = month + "月" + dates + "日";
}
var setSelect = function (newDate_year, newDate_month) {
    $('.select.year .text').html(newDate_year);
    $('.select.month .text').html(newDate_month);
    var yearStr = '';
    for (var i = newDate_year; i < newDate_year + 30; i++) {
        yearStr += '<li class="' + (i == newDate_year ? 'choosed' : '') + '">' + i + '</li>';
    }
    $('.select.year .options').html(yearStr);
    var monthStr = '';
    for (var i = 1; i <= 12; i++) {
        monthStr += '<li class="' + (i == newDate_month ? 'choosed' : '') + '">' + i + '</li>';
    }
    $('.select.month .options').html(monthStr);
    $('.select').on('click', function (e) {
        e.stopPropagation();
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
        } else {
            $(this).addClass('selected');
        }
    })
    $('.select ol li').on('click', function (e) {
        var $select = $(this).html();
        $(this).addClass('choosed').siblings().removeClass('choosed');
        $(this).parents('select').removeClass('selected');
        $(this).parent().siblings('.text').html($select);
        monthStr = $('.content.show .select.year .text').html() + '-' + $('.content.show .select.month .text').html()
        fileUrl_sum = '/json/hituns/tramendous?date=' + monthStr + '-&sum=true';
        fileUrl_notsum = '/json/hituns/tramendous?date=' + monthStr + '-&sum=false';
        for (var i in subCount) {
            fileUrl_sum += ('&' + i + '=' + subCount[i].split('、').length);
            fileUrl_notsum += ('&' + i + '=' + subCount[i].split('、').length);
        }
        getData.sum(fileUrl_sum, fileUrl_notsum);
    })
    $('body').on('click', function () {
        $('.select').removeClass('selected');
    })
}
var getData = {
    sum: function (fileUrl_sum) {
        var hituns = {};
        $.when($.get(fileUrl_sum), $.get(fileUrl_notsum)).done(function (data1, data2) {
            hituns.sum = typeof data1[0] == 'string' ? JSON.parse(data1[0]) : data1[0];
            hituns.notsum = typeof data2[0] == 'string' ? JSON.parse(data2[0]) : data2[0];
            hituns.notsumFormat = [];
            hituns.sum.sums.map(function (item, key) {
                hituns.sum.sums[key] = item;//(item / 100000000).toFixed(2) - 0;
            })
            $.each(hituns.notsum, function (key, item) {
                if (key == 'airport' || key == '') return false;
                for (var i in item) {
                    hituns.notsum[key][i] = item[i];//(item[i] / 100000000).toFixed(2) - 0;
                }
                hituns.notsumFormat.push({
                    data: item,
                    name: nameChange[key]
                })
            })
            $('.Chart').highcharts({
                chart: {
                    type: 'spline',
                    backgroundColor: '#1e5287',
                    zoomType: 'xy'
                },
                title: {
                    text: null,
                },
                xAxis: {
                    categories: hituns.sum.dates,
                    plotLines: [{
                        color: 'f5f5f5',            //线的颜色，定义为红色
                        dashStyle: 'solid',//标示线的样式，默认是solid（实线），这里定义为长虚线
                        width: 1                 //标示线的宽度，2px
                    }],
                    tickPosition: 'inside',
                    tickmarkPlacement: 'on',
                    startOnTick: true,
                    endOnTick: true,
                    labels: {
                        style: {
                            color: '#fff'
                        }
                    },
                    type: 'datetime'
                },
                yAxis: {
                    // allowDecimals: false,
                    title: {
                        align: "high",
                        rotation: 0,
                        text: '(条)',
                        style: {
                            color: '#fff'
                        }
                    },
                    labels: {
                        style: {
                            color: '#fff'
                        }
                    }
                },
                tooltip: {
                    backgroundColor: '#798697',
                    style: {
                        color: 'white'
                    },
                    formatter: function () {
                        var y = this.y.toString();
                        var s = this.key + '<br/>';
                        if (y.length >= 8) y = ((y - 0) / 100000000).toFixed(2) + '亿条';
                        else if (y.length >= 4 && y.length < 8) y = ((y - 0) / 10000).toFixed(2) + '万条';
                        else y = y + '条';
                        s += this.series.name + ' ' + y;
                        return s;
                    }
                },
                legend: {
                    enabled: false
                },
                credits: {
                    enabled: false
                },
                series: hituns.notsumFormat.concat([{ name: '总量', data: hituns.sum.sums, color: '#00FF30' }]),
            });
        })

    },
    notSum: function (fileUrl) {

        $.get(fileUrl, function (data) {
            hituns_now = typeof data == 'string' ? JSON.parse(data) : data;
            var indexs = [];
            if (!$('.lineContent.tramendous li').length) {
                for (var i in hituns_now) {
                    var title = '';
                    switch (i) {
                        case 'adsb':
                            title = nameChange[i];
                            indexs[4] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        case 'ais':
                            title = nameChange[i];
                            indexs[3] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        case 'traffic':
                            title = nameChange[i];
                            indexs[9] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        case 'airport':
                            title = nameChange[i];
                            indexs[10] = hituns_now[i] > 0 ? '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>' : '';
                            break;
                        case 'gps_js':
                            title = nameChange[i];
                            indexs[2] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        case 'gps_sh':
                            title = nameChange[i];
                            indexs[1] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        case 'gps_zj':
                            title = nameChange[i];
                            indexs[0] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        case 'ali':
                            title = nameChange[i];
                            indexs[8] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        case 'yys':
                            title = nameChange[i];
                            indexs[7] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        case 'taxi':
                            title = nameChange[i];
                            indexs[11] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            // indexs[11] = '';
                            break;
                        case 'gsevent':
                            title = nameChange[i];
                            indexs[5] = hituns_now[i] > 0 ? '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>' : '';
                            break;
                        case 'gskk':
                            title = nameChange[i];
                            indexs[6] = '<li class="lineSingle ' + i + '"><p class="title">' + title.toUpperCase() + '</p></li>';
                            break;
                        default:
                            break;
                    }
                }
                $('.lineContent.tramendous').html(indexs.join(''))
            }
            for (var i in hituns_now) {
                var text = '<s></s><s></s>';
                var num = hituns_now[i].toString().length;
                switch (true) {
                    case num <= 4:
                        text += '<span><b>' + hituns_now[i] + '</b>条</span>';
                        break;
                    case num <= 8 && num > 4:
                        text += '<span><b>' + (hituns_now[i] / 10000).toFixed(2) + '</b>万条</span>';
                        break;
                    case num > 8:
                        text += '<span><b>' + (hituns_now[i] / 100000000).toFixed(2) + '</b>亿条</span>';
                        break;
                    default:
                        break;
                }
                // $('.' + i + ' div.single').length > 0 ? $('.' + i + ' div.single s').removeClass('active') : $('.' + i + '').append('<div class="single">' + text + '</div>');
                // switch (true) {
                //     case num <= 4:
                //         $('.' + i + ' div').scrollValue({
                //             value: num,
                //             left: '',
                //             right: '条',
                //             color: '',
                //             fixed: 2,
                //             max: 20
                //         });
                //         break;
                //     case num <= 8 && num > 4:
                //         $('.' + i + ' div').scrollValue({
                //             value: num,
                //             left: '',
                //             right: '万条',
                //             color: '',
                //             fixed: 2,
                //             max: 20
                //         });
                //         break;
                //     case num > 8:
                //         $('.' + i + ' div').scrollValue({
                //             value: num,
                //             left: '',
                //             right: '亿条',
                //             color: '',
                //             fixed: 2,
                //             max: 20
                //         });
                //         break;
                //     default:
                //         break;
                // }
                $('.' + i + ' div.single').length > 0 ? $('.' + i + ' div.single').html(text) : $('.' + i + '').append('<div class="single">' + text + '</div>');
                $('.lineContent.tramendous s').addClass('active');
            }
        })
    }
}
$(function () {
    setSelect(newDate_year, newDate_month);
    monthStr = $('.content.show .select.year .text').html() + '-' + $('.content.show .select.month .text').html()
    fileUrl_sum = '/json/hituns/tramendous?date=' + monthStr + '-&sum=true';
    fileUrl_notsum = '/json/hituns/tramendous?date=' + monthStr + '-&sum=false';
    for (var i in subCount) {
        fileUrl += ('&' + i + '=' + subCount[i].split('、').length);
        fileUrl_sum += ('&' + i + '=' + subCount[i].split('、').length);
        fileUrl_notsum += ('&' + i + '=' + subCount[i].split('、').length);
    }
    getData.sum(fileUrl_sum, fileUrl_notsum);
    getData.notSum(fileUrl);
    setInterval(function () {
        getData.notSum(fileUrl);
    }, 3000);
    $('nav li').on('click', function () {
        var flag = $(this).hasClass('selected');
        if (!flag) {
            var index = $(this).index();
            $(this).addClass('selected').siblings().removeClass('selected');
            $('.content').removeClass('show').eq(index).addClass('show')
        }
    })
    $('.lines').on('click', '.right', function () {
        if ($('.content.show .lineContent li').length == 0) return false;
        var perWidth = $('.lineContent li').width() * 5;  //显示的宽度
        var totalWidth = $('.lineContent li').width() * $('.lineContent li').length - 0;//总宽度
        var leftDistance = $('.lineContent li').eq(0).offset().left - $('.lineContent').offset().left; //左边距离
        if (leftDistance - perWidth > -totalWidth) $('.content.show .lineContent li').eq(0).css({ 'margin-left': leftDistance - perWidth })
        else $('.content.show .lineContent li').eq(0).css({ 'margin-left': 0 })
    })
    $('.lines').on('click', '.left', function () {
        if ($('.content.show .lineContent li').length == 0) return false;
        var perWidth = $('.lineContent li').width() * 5;  //显示的宽度
        var totalWidth = $('.lineContent li').width() * $('.lineContent li').length - 0; //总宽度
        var leftDistance = $('.lineContent li').eq(0).offset().left - $('.lineContent').offset().left;  //左边距离
        if (leftDistance < 0) $('.content.show .lineContent li').eq(0).css({ 'margin-left': leftDistance + perWidth })
        else {
            var leftX = $('.content.show .lineContent li').length % 5; //除余
            leftDistance = totalWidth - perWidth / 5 * (!leftX ? 5 : leftX);
            $('.content.show .lineContent li').eq(0).css({ 'margin-left': -leftDistance })
        }
    })
    $('.line .lines .lineContent').on("mouseenter mouseleave", 'li.lineSingle', function (event) {
        event.stopPropagation();
        if (event.type == "mouseenter") {
            var _name = $(this).attr('class').replace(/lineSingle\s/, '');
            var _subs = subCount[_name].split('、');
            var _length = _subs.length;
            var lists = $('.lists');
            if (lists.length > 0) {
                lists.html('');
                if (lists.find('li').length == 0) {
                    for (var i = 0; i < _length; i++) {
                        var _li = $('<li>' + _subs[i] + '</li>');
                        $('.lists').append(_li);
                        !function (i) {
                            setTimeout(function () {
                                $('.lists li').eq(i).addClass('show');
                            }, 100 * i)
                        }(i)
                    }
                }
                lists = $('.lists');
                lists.show();
            } else {
                var str = '<ul class="lists">';
                str += '</ul>'
                $('main').append(str);
                for (var i = 0; i < _length; i++) {
                    var _li = $('<li>' + _subs[i] + '</li>');
                    $('.lists').append(_li);
                    !function (i) {
                        setTimeout(function () {
                            $('.lists li').eq(i).addClass('show');
                        }, 100 * i)
                    }(i)
                }
                lists = $('.lists');
                lists.show();
            };
            var left = $(this).offset().left;
            var top = $(this).offset().top;
            lists.css({
                left: left + 40 + 'px',
                bottom: window.outerHeight - window.scrollY - top + 'px'
            })
        } else if (event.type == "mouseleave") {
            $('.lists').hide();
        }
    })
})

